package se.zens.demo.wsapp.implementation;

import java.math.BigDecimal;
import java.util.Currency;

import se.zens.demo.wsapp.implementation.exceptions.InvalidCurrencyException;
import se.zens.demo.wsapp.implementation.exceptions.InvalidExchangeRateException;
import se.zens.demo.wsapp.interfaces.model.ExchangeRate;

public abstract class AbstractWSAppProcessor<E>
{
	protected void validateExchangeRate(ExchangeRate rate) throws InvalidCurrencyException, InvalidExchangeRateException
	{
		getCurrency(rate.getFromCurrency());
		getCurrency(rate.getToCurrency());
		if(rate.getRate() == null)
		{
			throw new InvalidExchangeRateException("Exchange rate is null");
		}	
		if(rate.getRate().compareTo(BigDecimal.ZERO) < 0)
		{
			throw new InvalidExchangeRateException("Exchange rate is negative");
		}	
	}
	
	protected Currency getCurrency(String currencyCode) throws InvalidCurrencyException
	{
		try
		{
			if(currencyCode == null)
			{
				throw new InvalidCurrencyException("currencyCode is null") ;
			}
			
			return Currency.getInstance(currencyCode);
		}
		catch(IllegalArgumentException ex)
		{
			throw new InvalidCurrencyException( currencyCode +" is invalid currency code");
		}
		
	}
	
	protected String getCurrencyPairKey(ExchangeRate rate)  throws InvalidCurrencyException
	{
		if(rate == null )
		{
			throw new InvalidCurrencyException("rate is null") ;
		}
		return getCurrencyPairKey(rate.getFromCurrency(),rate.getToCurrency());
	}
	
	protected String getCurrencyPairKey(String fromCurrency,String toCurrency)  throws InvalidCurrencyException
	{
		if(fromCurrency == null || toCurrency == null)
		{
			throw new InvalidCurrencyException("currency is null") ;
		}
		getCurrency(fromCurrency);
		getCurrency(toCurrency);
		return fromCurrency.toUpperCase() + "_" + toCurrency.toLowerCase();
	}
}
